package customerEnter.Frame.WebScoketChat;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import net.sf.json.JSONObject;

/**
 * 基於webscoket 的實現
 * 
 * 类名称：ServerCode 类描述： 创建人：dy 创建时间：2016-4-16 上午9:18:09
 * 
 */
@ServerEndpoint("/serverCode/{userName}/{userId}")
public class ServerCode {

	@OnOpen
	public void onOpen(@PathParam("userName")
	String userName, @PathParam("userId")
	Integer userId, Session session) {
		Boolean bool = false;
		String UUID = null;
		if (ChatServiceInformation.getChatMap() != null) {
			// 循環查找 有沒有相同賬號
			for (Entry<String, ChatUser> user : ChatServiceInformation.getChatMap().entrySet()) {
				if (userId.equals(user.getValue().getUserId())) {
					bool = true;
					UUID = user.getKey();
				}
			}
			// 如果沒有
			if (!bool) {
				ChatServiceInformation.setChatMap(session.getId(), new ChatUser(userName, userId, session));
			} else {
				ChatServiceInformation.getChatMap().get(UUID).setSession(session);
			}
		} else {
			ChatServiceInformation.setChatMap(session.getId(), new ChatUser(userName, userId, session));
		}
		JSONObject jsonObject = new JSONObject();
		int i = 0;
		for (Entry<String, ChatUser> iterable : ChatServiceInformation.getChatMap().entrySet()) {
			jsonObject.put("user" + i,
					setJsonObject(iterable.getValue().getUserId(), iterable.getValue().getUserName(), null, "已上線"));
			i++;
		}
		setChatMap(ChatServiceInformation.getChatMap().entrySet(), jsonObject);
	}

	@OnMessage
	public void onMessage(@PathParam("userName")
	String userName, @PathParam("userId")
	Integer userId, String message, Session session) {
		setChatMap(ChatServiceInformation.getChatMap().entrySet(), setJsonObject(userId, userName, message, null));
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		String UUID = "";
		for (Entry<String, ChatUser> iterable : ChatServiceInformation.getChatMap().entrySet()) {
			if (iterable.getValue().getSession().getId().equals(session.getId())) {
				UUID = iterable.getKey();
			}
		}
		ChatServiceInformation.getChatMap().remove(UUID);
	}

	/**
	 * 封裝發送的json
	 */
	public JSONObject setJsonObject(Integer userId, String userName, String message, String type) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userId", userId);
		jsonObject.put("userName", userName);
		jsonObject.put("message", message);
		jsonObject.put("type", type);
		return jsonObject;
	}

	/**
	 * 封裝發送的用戶信息
	 */
	public void setChatMap(Set<Entry<String, ChatUser>> users, JSONObject jsonObject) {
		try {
			for (Entry<String, ChatUser> user : users) {
				user.getValue().getSession().getBasicRemote().sendText(jsonObject.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
